package com.hmall.item.web;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.common.dto.PageDTO;
import com.hmall.common.dto.RequestParams;
import com.hmall.common.pojo.Item;
import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.service.IItemService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/item")
public class ItemController {

    @Autowired
    private IItemService itemService;




    /**
     * 分页查询
     *
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/list")
    public PageDTO<Item> page(@RequestParam Integer page, @RequestParam Integer size) {
        IPage<Item> itemPage = new Page<>(page, size);
        IPage<Item> page1 = itemService.page(itemPage);
        return PageDTO.of(page1.getTotal(), page1.getRecords());
    }


    /**
     * 根据id查询商品
     */
    @GetMapping("/{id}")
    public Item selectById(@PathVariable String id) {
        return itemService.getById(id);
    }


    /**
     * 新增商品
     */
    @PostMapping
    public void insertItem(@RequestBody Item item) {
        item.setCreateTime(new Date());
        itemService.save(item);
    }


    @Autowired
    private RabbitTemplate rabbitTemplate;
    /**
     * 商品上下架
     */
    @PutMapping("/status/{id}/{status}")
    public void openOrClose(@PathVariable String id, @PathVariable Integer status) {
        LambdaUpdateWrapper<Item> luw = new LambdaUpdateWrapper<>();
        luw.set(Item::getStatus, status)
                .eq(Item::getId, id);
        itemService.update(luw);
        //上下架商品需要及时更新缓存中的热销商品列表，使用RabbitMQ异步处理
        rabbitTemplate.convertAndSend("item.queue",id);
    }

    /**
     * 修改商品
     */
    @PutMapping
    public void updateItem(@RequestBody Item item) {
        LambdaUpdateWrapper<Item> luw = new LambdaUpdateWrapper<>();
        item.setUpdateTime(new Date());
        luw.set(Item::getName, item.getName())
                .set(Item::getCategory, item.getCategory())
                .set(Item::getBrand, item.getBrand())
                .set(Item::getPrice, item.getPrice())
                .set(Item::getStock, item.getStock())
                .set(Item::getSpec, item.getSpec())
                .set(Item::getImage, item.getImage())
                .set(Item::getIsAD, item.getIsAD())
                .set(Item::getUpdateTime, item.getUpdateTime())
                .eq(Item::getId, item.getId());
        //上述是方法1
        //方法2也可以设置条件构造器，然后eq 方法设置id
        //itemService.update(item,luw);
        itemService.update(null, luw);
    }


    /**
     * 删除商品（删除数据库数据）
     */
    @DeleteMapping("/{id}")
    public void deleteById(@PathVariable String id) {
        itemService.removeById(id);
    }


    @Autowired
    private ItemMapper itemMapper;

    /**
     * 过滤项聚合功能
     */
    @PostMapping("/filters")
    public Map searchFilters(@RequestBody RequestParams requestParams) {

        List<String> list1 = itemMapper.selectToList1();
        List<String> list2 = itemMapper.selectToList2(requestParams.getCategory());
        Map<String, List<String>> map = new HashMap<>();
        map.put("category", list1);
        map.put("brand", list2);
       // System.err.println(UserContext.getUserId());
        return map;

    }


    /**
     * 基本搜索功能
     */
    @PostMapping("/searchList")
    public PageDTO<Item> page(@RequestBody RequestParams requestParams) {
        return itemService.selectSimpleSearch(requestParams);
    }


    /**
     * 扣减库存
     */
    @PutMapping("/stock/{itemId}/{num}")
    public void stockNum(@PathVariable Long itemId,@PathVariable Integer num){
        LambdaUpdateWrapper<Item> luw = new LambdaUpdateWrapper<>();
        Item item = itemService.getById(itemId);
        luw.set(Item::getStock,item.getStock()-num)
                .set(Item::getUpdateTime,new Date())
                .set(Item::getSold,item.getSold()+num)
                .eq(Item::getId,itemId);
        itemService.update(item,luw);
    }

    /**
     * 恢复库存
     * @param itemId
     * @param num
     */
    @PutMapping("/{itemId}/{num}")
    public void runNum(@PathVariable Long itemId,@PathVariable Integer num){
        LambdaUpdateWrapper<Item> luw = new LambdaUpdateWrapper<>();
        Item item = itemService.getById(itemId);
        luw.set(Item::getStock,item.getStock()+num)
                .set(Item::getUpdateTime,new Date())
                .set(Item::getSold,item.getSold()-num)
                .eq(Item::getId,itemId);
        itemService.update(item,luw);
    }
}
